#include<string.h>
#include<malloc.h>

#include"battle.h"

Battle* create_battle(){
    Battle * this=(Battle*)calloc(1,sizeof(Battle));
    this->round_number=-1;
    this->user_hp=BATTLE_INIT_HP;
    this->enemy_hp=BATTLE_INIT_HP;
    this->user_action=READY;
    this->enemy_action=READY;
    return this; 
}

int judge(ACTION action1,ACTION action2){
    if(action1 == STONE && action2==CLOTH){
        return -1;
    }else if(action1==CLOTH && action2==SCISSOR){
        return -1;
    }if(action1==SCISSOR && action2==STONE){
        return -1;
    }else{
        return 0;
    }
}

int action_battle(Battle* this,char name[USER_NAME_LEN+1],ACTION action){
    int is_user=0;
    if(strncmp(this->user_name,name,USER_NAME_LEN)==0){
        is_user=1;
    }

    if(is_user){
        this->user_action=action;
        if(this->enemy_action==READY){
            return 0;//需要继续等待
        }
    }else{
        this->enemy_action=action;
        if(this->user_action==READY){
            return 0;//需要继续等待
        }
    }
    return 1;//需要返回消息
}

void finish_action(Battle* this){
    this->round_number++;
    this->user_hp+=judge(this->user_action,this->enemy_action);
    this->enemy_hp+=judge(this->enemy_action,this->user_action);
    this->user_action=READY;
    this->enemy_action=READY;
}

int is_user_lose(Battle* this){
    int user_hp=this->user_hp+judge(this->user_action,this->enemy_action);
    if(user_hp==0){
        return 1;
    }else{
        return 0;
    }
}   

int is_enemy_lose(Battle* this){
    int enemy_hp=this->enemy_hp+judge(this->enemy_action,this->user_action);
    if(enemy_hp==0){
        return 1;
    }else{
        return 0;
    }
}

int is_battle_ended(Battle* this){
    return (is_user_lose(this) || is_enemy_lose(this));
}

Battle* destory_battle(Battle* this){
    if(this==NULL)return NULL;
    free(this);
    return NULL;
}
